import React from 'react'
import {Row, Col, Button, Table, Select, Input, Avatar, Modal, message, Checkbox, Switch} from 'antd'
// import { UserOutlined } from '@ant-design/icons';
import './styles.css'
import Model from "./Model"
import api from "../../api/api";
import axios from 'axios';
import { Divider } from 'antd';


const {Search} = Input;
const {Option} = Select;


class RoomManager extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            modelData: {
                title: "新增人员",
                visible: false,
                type: 1,//新增人员:1,添加 2,编辑
                gridList: {},

            },
            title: "人员管理",
            visible: false,
            data: [],
            pageNum: 1,
            pageSize: 10,
            total: 0,
            selectedRowIds:[],
            hiddenFlag:true,
            areaId: undefined,
            roomName:undefined,
            priceFrom: "",
            priceTo: "",
            selectSwitchId:1,
            isUsed:undefined,
            param:{
                id:undefined,
                isUserd:undefined
            }



        };
    }


    componentDidMount() {
        this.getRoomManagerList();//查询全部
        this.getAreaCodeSelect();//区域下拉列表
      }
   columns = [
       {
           title: 'id',
           dataIndex: 'id',
           key: 'id',
          // className: "elementHidden",
           width: '1px'
       },
       {
           title: '区域编号',
           dataIndex: 'areaId',
           className: "elementHidden",
           key: 'areaId',
           width: '10px'
       },
       {
           title: '区域名称',
           dataIndex: 'areaName',
           key: 'areaName',
           width: '10px'
       },
        {
            title: '房间号',
            dataIndex: 'roomName',
            width: '15px',
            key: 'roomName'
        },
        {
            title: '房间类型',
            dataIndex: 'roomType',
            width: '15px',
            key: 'roomType'
        },
        {
            title: '房间价格',
            dataIndex: 'roomPrice',
            width: '15px',
            key: 'roomPrice'
        },
       {
           title: '状态',
           dataIndex: 'status',
           width: '15px',
           key: 'status'
       },
       {
           title: '创建时间',
           dataIndex: 'createTime',
           width: '15px',
           key: 'createTime'
       },
       {
           title: '更新时间',
           dataIndex: 'updateTime',
           width: '15px',
           key: 'updateTime'
       },
       {
           title: '禁用',
           dataIndex: 'isUsed',
           className: "elementHidden",
           width: '15px',
           key: 'isUsed'
       },
        {
            title: '操作',
            dataIndex: 'option',
            width: '15px',
            key: 'option',
            render: (_ext, record, Item) => {
                    return (
                    <span>
                       <a className="optionMargin" onClick={() => this.onClickEdit(record)}>编辑</a>
                       <a className="optionMargin" onClick={() => this.onClickDelete(record.id)}>删除</a>
                       <Switch checkedChildren="禁用" unCheckedChildren="启用" checked={record.isUsed === 1 ? true:false} onClick={() => this.selectSwitch(record)}  />
                    </span>
                    )
            }
        }
    ];


    getRoomManagerList() {
        let that = this;
        axios.post(api.api_URL + "/roommanager/selectAllRoom?pageNum=" + this.state.pageNum + "&pageSize=" + this.state.pageSize, {
            "roomName": this.state.roomName,
            "areaId":this.state.areaId,
            "priceFrom":this.state.priceFrom,
            "priceTo":this.state.priceTo,
        }, {
            headers: {
                "Content-Type": api.ContentType
            }
        }).then(function (res) {
          console.info(res)
            if (res.data.errorCode != 1) {
                return;
            }
            let totalSize = res.data.object.total;
            const dataList = [];
            for (let i = 0; i < res.data.object.records.length; i++) {
                let resContent = res.data.object.records[i];
                const content = {};
                content.key = (i + 1);
                content.id = resContent.id;
                content.areaId = resContent.areaId;
                if (resContent.areaId===1) {
                    content.areaName="天津和平区";
                }else if(resContent.areaId===2){
                    content.areaName="天津南开区";
                }
                content.roomName = resContent.roomName;
                content.roomType=resContent.roomType;
                content.roomPrice = resContent.roomPrice;
                if (resContent.status===0) {
                    content.status="未入住";
                }else if(resContent.status===1){
                    content.status="已入住";
                }else if(resContent.status===2){
                    content.status="已预订";
                }
                content.createTime = resContent.createTime;
                content.updateTime = resContent.updateTime;
                content.isUsed =resContent.isUsed;
                dataList[i] = content;
            }
            that.setState({
                data: dataList,
                total: totalSize
            })
        }).catch(function (err) {
            console.log(err);
        });
    }

    //通过id找到区域名字
    getAreaById(id){
        let that = this;
        axios.post(api.api_URL + "/hotelArea/selectAreaById?id=" + id , {
        }, {
            headers: {
                "Content-Type": api.ContentType
            }
        }).then(function (res) {
            console.log(res)
            that.setState({
                areaName: res.data.object.areaName

            })
        }).catch(function (err) {
            console.log(err);
        })
    }

    //单行启用禁用
    selectSwitch(item){
        let that = this;
        if(item.isUsed===0){
            item.isUsed=1
        }else if(item.isUsed===1) {
            item.isUsed=0
        }
        console.log(item)

        this.setState({
            param:{
                id:item.id,
                isUsed:item.isUsed
            }
        },()=> {
            this.selectSwitchdo();
        });

    }
    //单行启用禁用请求
    selectSwitchdo(){
        console.log(this.state.param);
        let that=this;
        axios({
            method: 'POST',
            url: api.api_URL + "/roommanager/updateRoomByRoomId",
            data: JSON.stringify(this.state.param),
            headers: {
                "Authorization": localStorage.getItem('token'),
                "Content-Type": "application/json;charset=UTF-8"
            },
        }).then(function (response) {
            if (response.data.errorCode != 1) {
                message.error({content: "失败，请重新尝试 ！"})
                return;
            }
            message.success({content: "成功！"})
            that.refresh()
        })
            .catch(function (error) {
                message.error({content: "失败，请重新尝试 ！"})
                console.log(error);
            })
     }

//分页
    onBaseClick(current, pageSize) {
        this.setState({
            pageNum: current,
            pageSize: pageSize
        }, () => {
            this.getRoomManagerList()
        });

    }

    onclickSearch() {
        console.info("搜索");
        this.getRoomManagerList();
    }



    //获取区域的下拉框
    areaCodeSelect = [];
    getAreaCodeSelect() {
        let that = this;
        let dataList = [];
        let url = api.api_URL + "/hotelArea/selectAllHotelArea";
        axios.get(url, {
            headers: {
                "Content-Type": api.ContentType
            }
        }).then(function (res) {
            console.info(res)
            if (res.data.errorCode != 1) {
                alert(res.data.msg);
                return;
            }
            let areaCodeList = res.data.objectList;
            for (let i = 0; i < areaCodeList.length; i++) {
                let comData = areaCodeList[i];
                const data = {};
                data.key = comData.id;
                data.label = comData.areaName;
                dataList[i] = data;
            }
            for (let i = 0; i < dataList.length; i++) {
                that.areaCodeSelect.push(<Option key={dataList[i].key}>{dataList[i].label}</Option>);

            }

        }).catch(function (err) {
            message.error({content:"加载失败，请重新尝试！"})
            console.log(err);
        })

    }


    //下拉框的改变值
    areaChange = (value) => {
        console.log(value)
        let that = this;
        this.setState({
            areaId: value
        })


    }

        departmentChange = (value) => {
            this.setState({
                selectDepartmentId: value
            })
        }

        inputChange = (e) => {
        console.log(e.target.value)
            this.setState({
                roomName: e.target.value
            })
        }
        priceFrom = (e) => {
            e.persist();
            console.log(e.target.value)
            this.setState({
                priceFrom: e.target.value
            })
        }

        priceTo = (e) => {
            e.persist();
            console.log(e.target.value)
            this.setState({
                priceTo: e.target.value
            })
        }

//删除
    onClickDelete(item) {
        let that = this;
        let configModel = Modal.confirm({
            title: '删除',
            content: '是否确认删除？',
            onOk: (values) => {
                return new Promise((res, rej) => {
                    let url = api.api_URL + "/roommanager/deleteRoomByid?id="+item;
                    axios.post(url, {
                        headers: {
                            "Authorization": localStorage.getItem('token'),
                            "Content-Type": api.ContentType
                        }
                    }).then(function (res) {
                        console.log(res)
                        if (res.data.errorCode != 1) {
                            message.error({content:"删除失败，请重新尝试！"})
                            return;
                        }
                        message.success({content:"删除成功！"})
                        that.setState({
                            data: []
                        })
                        that.getRoomManagerList();
                        configModel.destroy();

                    }).catch(function (err) {
                        message.error({content:"删除失败，请重新尝试！"})

                        console.log(err);
                    })
                }).catch((e) => console.warn(e));
            },
            onCancel() {
            },
        })
    }
    //批量删除
    onClickDeletes(){
        let that = this;
        let configModel = Modal.confirm({
            title: '删除',
            content: '是否确认删除？',
            onOk: (values) => {
                return new Promise((res, rej) => {
                    let url = api.api_URL + "/roommanager/deleteRoomByBatchIds";
                    axios.post(url, {
                        "id": this.state.selectedRowIds,
                    },{
                        headers: {
                            "Authorization": localStorage.getItem('token'),
                            "Content-Type": api.ContentType
                        }
                    }).then(function (res) {
                        console.log(res)
                        if (res.data.errorCode != 1) {
                            message.error({content:"删除失败，请重新尝试！"})
                            return;
                        }
                        message.success({content:"删除成功！"})
                        that.setState({
                            data: []
                        })
                        that.getRoomManagerList();
                        configModel.destroy();

                    }).catch(function (err) {
                        message.error({content:"删除失败，请重新尝试！"})
                        console.log(err);
                    })
                }).catch((e) => console.warn(e));
            },
            onCancel() {
            },
        })
    }
//编辑
    onClickEdit(item) {
        if (item.areaId==1) {
            item.areaId="天津和平区"
        }
        if (item.areaId==2) {
            item.areaId="天津南开区"
        }
        this.setState({
            modelData: {
                title: "编辑",
                type: 2,
                visible: true,
                gridList: item,

            }
        }, () => {
            this.child.initEditData()
        });
    }

    //添加
    addPersion() {
        this.setState({
            modelData: {
                title: "新增人员",
                type: 1,
                visible: true
            }
        }, () => {
            this.child.clearData()
        });
    }

    onclickReset() {
        this.setState({
            areaId:undefined,
            roomName:undefined,
            priceTo: "",
            priceFrom:"",
        },() => {
            this.getRoomManagerList()
        });

    };
    //设置启用状态
    onclickSetIdentify(){
        console.log("this.state.selectedRowIds",this.state.selectedRowIds)
        if (this.state.selectedRowIds == null || this.state.selectedRowIds.length == 0){
            message.error({content:"请选择需要设置的行"})
            return;
        }
        this.setState({
            visible: true,
        })
    }

    handleOk = e => {
        console.log(e);
        this.setState({
            visible: false,
        });
    };

    handleOkForIdentify= e =>{
        let that=this;
        let url = api.api_URL + "/roommanager/updateIsUsedByRoomIds";
        axios.post(url, {
                "id":this.state.selectedRowIds,
                "isUsed":this.state.isUsed
        },{
            headers: {
                "Authorization": localStorage.getItem('token'),
                "Content-Type": api.ContentType
            }
        }).then(function (res) {
            that.handleCancel()
            if (res.data.errorCode==1) {
                message.success({content:"状态设置成功！"})
            }else{
                message.error({content:"状态设置失败！"})
            }
        }).catch(function (err) {
            console.log(err);
        });
        that.setState({
            hiddenFlag:true,
            isUsed:undefined,
        })


    }

    //设置状态的改变事件
    identifyChange=(value)=>{
        console.log(value)
        this.setState({
            isUsed: value,
        })
    }
    //取消
    handleCancel = e => {
        this.setState({
            visible:false,
            c1:false,
            c2:false,
            isUsed:undefined,
            hiddenFlag:true,
            modelData: {
                visible: false
            },
        }, () => {
            this.refresh()
        });

    }



    refresh() {
        this.getRoomManagerList()
    }

    onRef = (ref) => {
        this.child = ref
    }



    render() {
        const {selectedRowKeys } = this.state;
        const CheckboxGroup = Checkbox.Group;
        const CheckBox=Checkbox;
        const rowSelection = {
            columnWidth:10,
            selectedRowKeys,
            onChange: (selectedRowKeys) => {
                this.setState({
                    selectedRowIds : selectedRowKeys.map(Number),
                    selectedRowKeys
                })
                console.log(`selectedRowKeys: ${selectedRowKeys}`);
            },
        };
        return (
            <div className="girdBg">
                <Row className="searchBox">
                    <Col span={12}>
                        <Select showSearch={true} optionFilterProp="children" placeholder="请选择区域" style={{width: 250, marginLeft: 30}} on onChange={this.areaChange} value={this.state.areaId} allowClear >
                            {this.areaCodeSelect}
                        </Select>
                        <Search style={{width: 250,marginLeft:30}}
                                placeholder="请输入房间号" onChange={this.inputChange}  allowClear value={this.state.roomName}
                        />
                    </Col>
                    <Col span={12} className="btnRight">
                        <Button icon={"delete"} type='primary' onClick={this.onClickDeletes.bind(this)}>批量删除</Button>
                        <Button icon={"save"} type='primary' style={{marginLeft: 30}} onClick={this.addPersion.bind(this)}>新增房间</Button>
                        <Button icon={"setting"} type='primary' style={{marginLeft: 30}} onClick={this.onclickSetIdentify.bind(this)}>设置启用状态</Button>
                    </Col>
                </Row>
                <Row className="searchBox">
                    <Col span={18}>
                        <input style={{width: 100,marginLeft:30}}
                               placeholder="请输入价格"  onChange={this.priceFrom} value={this.state.priceFrom} allowClear
                        />
                        <span  style={{width: 10,marginLeft:15}}>  ---   </span>
                        <input style={{width: 100,marginLeft:15}}
                               placeholder="请输入价格" onChange={this.priceTo} value={this.state.priceTo} allowClear
                        />
                        <Button icon={"search"} type='primary' style={{marginLeft: 30}}
                                onClick={this.onclickSearch.bind(this)}>搜索</Button>
                        <Button icon={"reset"} style={{marginLeft: 30}} onClick={this.onclickReset.bind(this)}>重置</Button>
                    </Col>
                </Row>
                <Row style={{margin: 30}}>
                    <Table
                        columns={this.columns}
                        dataSource={this.state.data}
                        scroll={{x: 'max-content'}} // 加上这条  横向滚动  支持此属性的浏览器内容就不会换行了
                        rowSelection={rowSelection}
                        rowKey={record =>record.id}
                        columns={this.columns.map(item => { // 通过配置 给每个单元格添加不换行属性
                            const fun = () => ({style: {whiteSpace: 'nowrap'}});
                            item.onHeaderCell = fun;
                            item.onCell = fun;
                            return item;
                        })}
                        pagination={{
                            simple: false,
                            current: this.state.pageNum,
                            total: this.state.total,
                            pageSize: this.state.pageSize,
                            showTotal: (count = this.state.total) => {
                                return '共' + count + '条'
                            },
                            onChange: (current, pageSize) => {
                                this.onBaseClick(current, pageSize)
                            }
                        }}
                    />
                </Row>
                <Model data={this.state.modelData} handleCancel={this.handleCancel} refresh={this.refresh}
                       onRef={this.onRef} history={this.props.history}/>
                <Modal title="设置状态信息"refresh={this.refresh}
                       visible={this.state.visible}
                       onOk={this.handleOkForIdentify}
                       onCancel={this.handleCancel}

                >
                   <Select style={{width: 300}} placeholder="请选择状态"  onChange={this.identifyChange} value={this.state.isUsed}>
                       <Option key="1">启用</Option>
                       <Option key="0">禁用</Option>

                   </Select>
                </Modal>
            </div>
        )
    }
}

export default RoomManager
